<?php

/**
 * Authentication control component class
 *
 * Binds access control with user authentication and session management.
 *
 * PHP versions 5
 * CAKEPHP versions 2.x
 * 
 * Green CMS - Content Management System and Framework Powerfull by Cakephp
 * Copyright 2012, GREEN GLOBAL CO., LTD (toancauxanh.vn)
 * 
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @author        Technology Lab No.I <tech1@toancauxanh.vn>
 * @link          
 * @package       Controller.Component
 * @since         Green v 1.0
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
App::uses('Component', 'Controller');
App::uses('Security', 'Utility');
App::uses('Debugger', 'Utility');
App::uses('Router', 'Routing');
App::uses('CakeSession', 'Model/Datasource');
App::uses('BaseAuthorize', 'Controller/Component/Auth');
App::uses('BaseAuthenticate', 'Controller/Component/Auth');
App::uses('BaseAntidetect', 'Controller/Component/Auth');

class AuthComponent extends Component {

    const ALL = 'all';

    /**
     * Other components utilized by AuthComponent
     *
     * @var array
     */
    public $components = array('Session');

    /**
     * An array of authentication objects to use for authenticating users.  You can configure
     * multiple adapters and they will be checked sequentially when users are identified.
     *
     * {{{
     * 	$this->Auth->authenticate = array(
     * 		'Form' => array(
     * 			'userModel' => 'Users.User'
     * 		)
     * 	);
     * }}}
     *
     * Using the class name without 'Authenticate' as the key, you can pass in an array of settings for each
     * authentication object.  Additionally you can define settings that should be set to all authentications objects
     * using the 'all' key:
     *
     * {{{
     * 	$this->Auth->authenticate = array(
     * 		'all' => array(
     * 			'userModel' => 'Users.User',
     * 			'scope' => array('User.active' => 1)
     * 		),
     * 		'Form',
     * 		'Basic'
     * 	);
     * }}}
     *
     * You can also use AuthComponent::ALL instead of the string 'all'.
     *
     * @var array
     * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
     */
    public $authenticate = array(
        'Form'
    );

    /**
     * Objects that will be used for authentication checks.
     *
     * @var array
     */
    protected $_authenticateObjects = array();

    /**
     * An array of authorization objects to use for authorizing users.  You can configure
     * multiple adapters and they will be checked sequentially when authorization checks are done.
     *
     * {{{
     * 	$this->Auth->authorize = array(
     * 		'Crud' => array(
     * 			'actionPath' => 'controllers/'
     * 		)
     * 	);
     * }}}
     *
     * Using the class name without 'Authorize' as the key, you can pass in an array of settings for each
     * authorization object.  Additionally you can define settings that should be set to all authorization objects
     * using the 'all' key:
     *
     * {{{
     * 	$this->Auth->authorize = array(
     * 		'all' => array(
     * 			'actionPath' => 'controllers/'
     * 		),
     * 		'Crud',
     * 		'CustomAuth'
     * 	);
     * }}}
     *
     * You can also use AuthComponent::ALL instead of the string 'all'
     *
     * @var mixed
     * @link http://book.cakephp.org/view/1275/authorize
     */
    public $authorize = array();

    /**
     * Objects that will be used for authorization checks.
     *
     * @var array
     */
    protected $_authorizeObjects = array();

    /**
     * Protect your system from detection tracking login information.
     * 
     * @see BaseAntidetect
     * @var array
     */
    public $antidetect = array();

    /**
     * Objects that will be used for detect password
     *
     * @see BaseAntidetect
     * @var array
     */
    protected $_antidetectObjects;

    /**
     * The name of an optional view element to render when an Ajax request is made
     * with an invalid or expired session
     *
     * @var string
     */
    public $ajaxLogin = null;

    /**
     * Settings to use when Auth needs to do a flash message with SessionComponent::setFlash().
     * Available keys are:
     *
     * - `element` - The element to use, defaults to 'default'.
     * - `key` - The key to use, defaults to 'auth'
     * - `params` - The array of additional params to use, defaults to array()
     *
     * @var array
     */
    public $flash = array(
        'element' => 'default',
        'key' => 'auth',
        'params' => array()
    );

    /**
     * The session key name where the record of the current user is stored.  If
     * unspecified, it will be "Auth.User".
     *
     * @var string
     */
    public static $sessionKey = 'Auth.User';

    /**
     * The current user, used for stateless authentication when
     * sessions are not available.
     *
     * @var array
     */
    protected static $_user = array();

    /**
     * A URL (defined as a string or array) to the controller action that handles
     * logins.  Defaults to `/users/login`
     *
     * @var mixed
     */
    public $loginAction = array(
        'controller' => 'users',
        'action' => 'login',
        'plugin' => null
    );

    /**
     * Normally, if a user is redirected to the $loginAction page, the location they
     * were redirected from will be stored in the session so that they can be
     * redirected back after a successful login.  If this session value is not
     * set, the user will be redirected to the page specified in $loginRedirect.
     *
     * @var mixed
     * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#AuthComponent::$loginRedirect
     */
    public $loginRedirect = null;

    /**
     * The default action to redirect to after the user is logged out.  While AuthComponent does
     * not handle post-logout redirection, a redirect URL will be returned from AuthComponent::logout().
     * Defaults to AuthComponent::$loginAction.
     *
     * @var mixed
     * @see AuthComponent::$loginAction
     * @see AuthComponent::logout()
     */
    public $logoutRedirect = null;

    /**
     * Error to display when user attempts to access an object or action to which they do not have
     * access.
     *
     * @var string
     * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#AuthComponent::$authError
     */
    public $authError = null;

    /**
     * Controller actions for which user validation is not required.
     *
     * @var array
     * @see AuthComponent::allow()
     */
    protected $_allowedActions = array();

    /**
     * Request object
     *
     * @var CakeRequest
     */
    public $request;

    /**
     * Response object
     *
     * @var CakeResponse
     */
    public $response;

    /**
     * Method list for bound controller
     *
     * @var array
     */
    protected $_methods = array();

    /**
     * Initializes AuthComponent for use in the controller
     *
     * @param Controller $controller A reference to the instantiating controller object
     * @return void
     */
    public function initialize(Controller $controller) {
        $this->request = $controller->request;
        $this->response = $controller->response;
        $this->_methods = array_map('strtolower', $controller->methods);

        if (Configure::read('debug') > 0) {
            Debugger::checkSecurityKeys();
        }
    }

    /**
     * Main execution method.  Handles redirecting of invalid users, and processing
     * of login form data.
     *
     * @param Controller $controller A reference to the instantiating controller object
     * @return boolean
     */
    public function startup(Controller $controller) {
        if ($controller->name == 'CakeError') {
            return true;
        }
        $request = $controller->request;

        $methods = array_flip(array_map('strtolower', $controller->methods));
        $action = strtolower($request->params['action']);

        $isMissingAction = (
                $controller->scaffold === false &&
                !isset($methods[$action]));

        if ($isMissingAction) {
            return true;
        }

        if (!$this->_setDefaults()) {
            return false;
        }

        $url = '';

        if (isset($request->url)) {
            $url = $request->url;
        }
        $url = Router::normalize($url);
        $loginAction = Router::normalize($this->loginAction);

        if ($loginAction != $url && $this->isAllowed($request)) {
            return true;
        }

        if ($loginAction == $url) {
            if (empty($request->data)) {
                if (!$this->Session->check('Auth.redirect') && !$this->loginRedirect && env('HTTP_REFERER')) {
                    $this->Session->write('Auth.redirect', $controller->referer(null, true));
                }
            }
            return true;
        } else {
            $user = $this->user();
            $message = $this->authError;
            if ($user && !$this->_isValidate($user)) {
                $user = null;
                $this->logout(false);
                $message = __d('green', 'You have been disconnected from the server. Please sign in againt.');
            } elseif (!$user) {
                $user = $this->_getUser();
            }
        }

        if (empty($this->authorize) || $this->isAuthorized($user)) {
            return true;
        }

        $this->flash($message);
        $here = $request->here(false);
        $this->Session->write('Auth.redirect', $here);
        if (!$request->is('ajax')) {
            if (is_array($loginAction)) {
                $loginAction = Router::normalize(Router::url($loginAction));
            }
            $controller->redirect($loginAction . '?' . http_build_query(array('continue' => $here), null, '&'));
        } elseif (!empty($this->ajaxLogin)) {
            $controller->viewPath = 'Elements';
            echo $controller->render($this->ajaxLogin, $this->ajaxLayout);
            $this->_stop();
        } else {
            $controller->redirect(null, 403);
        }
        return false;
    }

    /**
     * Attempts to introspect the correct values for object properties.
     *
     * @return boolean
     */
    protected function _setDefaults() {
        $defaults = array(
            'logoutRedirect' => $this->loginAction,
            'authError' => __d('green', 'Oops! Access denied . You are not authorized to access that location.')
        );
        foreach ($defaults as $key => $value) {
            if (empty($this->{$key})) {
                $this->{$key} = $value;
            }
        }
        return true;
    }

    /**
     * Get allowed action.
     *
     * @return array
     */
    public function allowedActions() {
        return $this->_allowedActions;
    }

    /**
     * Check allowed for action.
     *
     * @param mixed $action Optional string action or CakeRequest object. If it not set the request of auth to use
     * @return mixed action to be checking . default is current action requested
     */
    public function isAllowed($action = null) {
        if (is_null($action)) {
            $action = $this->request;
        }
        if ($action instanceof CakeRequest) {
            $action = $action->params['action'];
        }
        return (in_array(strtolower($action), $this->_allowedActions));
    }

    /**
     * If no parameter is passed, gets the authentication redirect URL.  Pass a url in to
     * set the destination a user should be redirected to upon logging in.  Will fallback to
     * AuthComponent::$loginRedirect if there is no stored redirect value.
     *
     * @param mixed $url Optional default URL to as the login redirect URL.
     * @return string Redirect URL
     */
    public function redirect($url = '/') {
        if (!empty($this->request->query['continue'])) {
            $redir = $this->request->query['continue'];
        } elseif ($this->Session->check('Auth.redirect')) {
            $redir = $this->Session->read('Auth.redirect');
            $this->Session->delete('Auth.redirect');
            if (Router::normalize($redir) == Router::normalize($this->loginAction)) {
                $redir = $this->loginRedirect;
            }
        } else {
            $redir = $this->loginRedirect;
        }
        if (!empty($redir)) {
            $url = $redir;
        }
        return Router::normalize($url);
    }

    /**
     * Uses the configured Authorization adapters to check whether or not a user is authorized.
     * Each adapter will be checked in sequence, if any of them return true, then the user will
     * be authorized for the request.
     *
     * @param mixed $user The user to check the authorization of. If an empty value will be check public authorize
     * @param CakeRequest $request The request to authenticate for.  If empty, the current request will be used.
     * @return boolean True if $user is authorized, otherwise false
     */
    public function isAuthorized($user = null, CakeRequest $request = null) {
        if (empty($user)) {
            $user = $this->user();
        }
        if (empty($request)) {
            $request = $this->request;
        }
        $this->constructAuthorize();
        foreach ($this->_authorizeObjects as $authorizer) {
            $result = $authorizer->authorize($user, $request);
            if ($result === '*') {
                $this->allow();
                return true;
            }
            if (is_array($result) && !empty($result)) {
                $this->allow($result);
                if ($this->isAllowed()) {
                    return true;
                }
                continue;
            }
            if ($result === true) {
                return true;
            }
        }
        return false;
    }

    /**
     * Loads the authorization objects configured.
     *
     * @return mixed Either null when authorize is empty, or the loaded authorization objects.
     * @throws CakeException
     */
    public function constructAuthorize() {
        if (empty($this->authorize) || $this->_authorizeObjects) {
            return $this->_authorizeObjects;
        }
        $config = Set::normalize($this->authorize);
        $global = array();
        if (isset($config[AuthComponent::ALL])) {
            $global = $config[AuthComponent::ALL];
            unset($config[AuthComponent::ALL]);
        }
        foreach ($config as $class => $settings) {
            list($plugin, $class) = pluginSplit($class, true);
            $className = $class . 'Authorize';
            App::uses($className, $plugin . 'Controller/Component/Auth');
            if (!class_exists($className)) {
                throw new CakeException(__d('debug', 'Authorization adapter "%s" was not found.', $class));
            }
            if (!method_exists($className, 'authorize')) {
                throw new CakeException(__d('debug', 'Authorization objects must implement an authorize method.'));
            }
            $settings = array_merge($global, (array) $settings);
            $this->_authorizeObjects[] = new $className($this->_Collection, $settings);
        }
        return $this->_authorizeObjects;
    }

    /**
     * Checking login was blocked by Anti detect
     * 
     * @return boolean true on is blocked, false on non block.
     */
    public function isDetector() {
        $this->constructAntidetect();
        foreach ($this->_antidetectObjects as $anti) {
            if ($anti->isBlocked()) {
                return true;
            }
        }
        return false;
    }

    /**
     * Loads the Antidetect objects configured.
     *
     * @return mixed Either null when antidetect is empty, or the loaded Antidetect objects.
     * @throws CakeException
     */
    public function constructAntidetect() {
        if (empty($this->antidetect) || $this->_antidetectObjects) {
            return $this->_antidetectObjects;
        }
        $config = Set::normalize($this->antidetect);
        $global = array();
        if (isset($config[AuthComponent::ALL])) {
            $global = $config[AuthComponent::ALL];
            unset($config[AuthComponent::ALL]);
        }
        foreach ($config as $class => $settings) {
            list($plugin, $class) = pluginSplit($class, true);
            $className = $class . 'Antidetect';
            App::uses($className, $plugin . 'Controller/Component/Auth');
            if (!class_exists($className)) {
                throw new CakeException(__d('debug', 'Antidetect adapter "%s" was not found.', $class));
            }
            $settings = array_merge($global, (array) $settings);
            $instance = new $className($this->_Collection, $settings);
            if (!($instance instanceof BaseAntidetect)) {
                throw new CakeException(__d('debug', 'Authentication objects must implement with BaseAntidetect class.'));
            }
            $this->_antidetectObjects[] = $instance;
        }
        return $this->_antidetectObjects;
    }

    /**
     * Takes a list of actions in the current controller for which authentication is not required, or
     * no parameters to allow all actions.
     *
     * You can use allow with either an array, or var args.
     *
     * `$this->Auth->allow(array('edit', 'add'));` or
     * `$this->Auth->allow('edit', 'add');`
     * `$this->Auth->allow();` to allow all actions.
     *
     * allow() also supports '*' as a wildcard to mean all actions.
     *
     * `$this->Auth->allow('*');`
     *
     * @param mixed $action,... Controller action name or array of actions
     * @return void
     * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-public
     */
    public function allow($action = null) {
        $args = func_get_args();
        if (empty($args) || $action === null) {
            $this->_allowedActions = $this->_methods;
        } else {
            if (isset($args[0]) && is_array($args[0])) {
                $args = $args[0];
            }
            $args = array_map('strtolower', $args);
            $this->_allowedActions = array_merge($this->_allowedActions, $args);
        }
    }

    /**
     * Removes items from the list of allowed/no authentication required actions.
     *
     * You can use deny with either an array, or var args.
     *
     * `$this->Auth->deny(array('edit', 'add'));` or
     * `$this->Auth->deny('edit', 'add');` or
     * `$this->Auth->deny();` to remove all items from the allowed list
     *
     * @param mixed $action,... Controller action name or array of actions
     * @return void
     * @see AuthComponent::allow()
     * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-require-authorization
     */
    public function deny($action = null) {
        $args = func_get_args();
        if (empty($args) || $action === null) {
            $this->_allowedActions = array();
        } else {
            if (isset($args[0]) && is_array($args[0])) {
                $args = $args[0];
            }
            foreach ($args as $arg) {
                $i = array_search(strtolower($arg), $this->_allowedActions);
                if (is_int($i)) {
                    unset($this->_allowedActions[$i]);
                }
            }
            $this->_allowedActions = array_values($this->_allowedActions);
        }
    }

    /**
     * Maps action names to CRUD operations. Used for controller-based authentication.  Make sure
     * to configure the authorize property before calling this method. As it delegates $map to all the
     * attached authorize objects.
     *
     * @param array $map Actions to map
     * @return void
     * @see BaseAuthorize::mapActions()
     * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#mapping-actions-when-using-crudauthorize
     */
    public function mapActions($map = array()) {
        $this->constructAuthorize();
        foreach ($this->_authorizeObjects as $auth) {
            $auth->mapActions($map);
        }
    }

    /**
     * Log a user in. If a $user is provided that data will be stored as the logged in user.  If `$user` is empty or not
     * specified, the request will be used to identify a user. If the identification was successful,
     * the user record is written to the session key specified in AuthComponent::$sessionKey. Logging in
     * will also change the session id in order to help mitigate session replays.
     *
     * @param mixed $user Either an array of user data, or null to identify a user using the current request.
     * @param mixed $antiDetector mixed $status, boolean if set activated/deactivated or null for does not change.
     * @return boolean True on login success, false on failure
     * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in
     */
    public function login($user = array(), $antiDetector = null) {
        $this->_setDefaults();
        $this->constructAntidetect();
        foreach ($this->_antidetectObjects as $anti) {
            $anti->activate($antiDetector);
        }
        if (!$user && !($user = $this->identify($this->request, $this->response))) {
            return false;
        }
        $this->Session->write(self::$sessionKey, $user);
        return $this->loggedIn();
    }

    /**
     * Logs a user out, and returns the login action to redirect to.
     * Triggers the logout() method of all the authenticate objects, so they can perform
     * custom logout logic.  AuthComponent will remove the session data, so
     * there is no need to do that in an authentication object.  Logging out
     * will also renew the session id.  This helps mitigate issues with session replays.
     *
     * @return string AuthComponent::$logoutRedirect
     * @see AuthComponent::$logoutRedirect
     * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out
     */
    public function logout() {
        $this->_setDefaults();
        $user = $this->user();
        $this->constructAuthenticate();
        foreach ($this->_authenticateObjects as $auth) {
            $auth->logout($user);
        }
        $this->Session->delete(self::$sessionKey);
        $this->Session->delete('Auth.redirect');
        $this->Session->renew();
        return Router::normalize($this->logoutRedirect);
    }

    /**
     * Get the current user.
     *
     * Will prefer the static user cache over sessions.  The static user
     * cache is primarily used for stateless authentication.  For stateful authentication,
     * cookies + sessions will be used.
     *
     * @param string $key field to retrieve.  Leave null to get entire User record
     * @return mixed User record. or null if no user is logged in.
     * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user
     */
    public static function user($key = null) {
        if (empty(self::$_user) && !CakeSession::check(self::$sessionKey)) {
            return null;
        }
        if (!empty(self::$_user)) {
            $user = self::$_user;
        } else {
            $user = CakeSession::read(self::$sessionKey);
        }
        if ($key === null) {
            return $user;
        }
        if (isset($user[$key])) {
            return $user[$key];
        }
        return null;
    }

    /**
     * Similar to AuthComponent::user() except if the session user cannot be found, connected authentication
     * objects will have their getUser() methods called.  This lets stateless authentication methods function correctly.
     *
     * @return boolean true if a user can be found, false if one cannot.
     */
    protected function _getUser() {
        $this->constructAuthenticate();
        foreach ($this->_authenticateObjects as $auth) {
            $result = $auth->getUser($this->request);
            if (!empty($result) && is_array($result)) {
                self::$_user = $result;
                return true;
            }
        }
        return false;
    }

    /**
     * Validate data was Authenticated.
     *
     * @param array $user data to validate.
     * @return mixed Either false on failure, true on success or void/null on skip
     */
    public function _isValidate($user) {
        $this->constructAntidetect();
        $this->constructAuthenticate();
        foreach ($this->_authenticateObjects as $auth) {
            $result = $auth->validate($user);
            if (is_bool($result)) {
                return $result;
            }
        }
        return true;
    }

    /**
     * Use the configured authentication adapters, and attempt to identify the user
     * by credentials contained in $request.
     *
     * @param CakeRequest $request The request that contains authentication data.
     * @param CakeResponse $response The response
     * @return array User record data, or false, if the user could not be identified.
     */
    public function identify(CakeRequest $request, CakeResponse $response) {
        $this->constructAuthenticate();
        foreach ($this->_authenticateObjects as $auth) {
            $result = $auth->authenticate($request, $response);
            if (!empty($result) && is_array($result)) {
                return $result;
            }
        }
        return false;
    }

    /**
     * loads the configured authentication objects.
     *
     * @return mixed either null on empty authenticate value, or an array of loaded objects.
     * @throws CakeException
     */
    public function constructAuthenticate() {
        if (empty($this->authenticate) || $this->_authenticateObjects) {
            return $this->_authenticateObjects;
        }
        $config = Set::normalize($this->authenticate);
        $global = array();
        if (isset($config[AuthComponent::ALL])) {
            $global = $config[AuthComponent::ALL];
            unset($config[AuthComponent::ALL]);
        }

        foreach ($config as $class => $settings) {
            list($plugin, $class) = pluginSplit($class, true);
            $className = $class . 'Authenticate';
            App::uses($className, $plugin . 'Controller/Component/Auth');
            if (!class_exists($className)) {
                throw new CakeException(__d('debug', 'Authentication adapter "%s" was not found.', $class));
            }
            $settings = array_merge($global, (array) $settings);
            $instance = new $className($this->_Collection, $settings);
            if (!($instance instanceof BaseAuthenticate)) {
                throw new CakeException(__d('debug', 'Authentication objects must implement with BaseAuthenticate class.'));
            }
            $this->_authenticateObjects[] = $instance;
        }
        return $this->_authenticateObjects;
    }

    /**
     * Hash a password with the application's salt value (as defined with Configure::write('Security.salt');
     *
     * This method is intended as a convenience wrapper for Security::hash().  If you want to use
     * a hashing/encryption system not supported by that method, do not use this method.
     *
     * @param string $password Password to hash
     * @return string Hashed password
     * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#hashing-passwords
     */
    public static function password($password) {
        return Security::hash($password, null, true);
    }

    /**
     * Component shutdown.  If user is logged in, wipe out redirect.
     *
     * @param Controller $controller Instantiating controller
     * @return void
     */
    public function shutdown(Controller $controller) {
        if ($this->loggedIn()) {
            $this->Session->delete('Auth.redirect');
        }
    }

    /**
     * Check whether or not the current user has data in the session, and is considered logged in.
     *
     * @return boolean true if the user is logged in, false otherwise
     */
    public function loggedIn() {
        return $this->user() != array();
    }

    /**
     * Set a flash message.  Uses the Session component, and values from AuthComponent::$flash.
     *
     * @param string $message The message to set.
     * @return void
     */
    public function flash($message) {
        $this->Session->setFlash($message, $this->flash['element'], $this->flash['params'], $this->flash['key']);
    }

}